package cn.soft863.common.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.soft863.common.util.VerifyCodeUtil;

public class CommonServlet  extends HttpServlet
{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String method = request.getParameter("method");
		if("randImg".equalsIgnoreCase(method)) {	
			randImg(request, response);
		}
		
	}

	private void randImg(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		//生成随机字符串
		String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
		//request.getSession(true)：若存在会话则返回该会话，否则新建一个会话。
		//request.getSession(false)：若存在会话则返回该会话，否则返回NULL。
		HttpSession session = request.getSession(true);
		session.setAttribute("rand",  verifyCode.toLowerCase());
		
		int w = 200, h = 80;
		VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode);
		
	}

}
